You can declare that a class implements an interface by delegation. To do that, pass in a concrete implementation of the interface into the class constructor, then use the by keyword as part of declaring that the class implements the interface. by sets up delegation: the class will support all of the functions and properties defined by the interface, but the implementation of those functions and properties will be delegated to the indicated object.

Int his case, our interface is FavoriteStore, for indicating whether some object is or is not a favorite (such as for bookmarks, social media posts, etc.). We have one concrete implementation of that interface in the form of InMemoryFavoriteStore, which uses a MutableMap to track the favorites. We have an Item class representing some model object and an ItemViewModel that might represent an Android Jetpack-style ViewModel. ItemViewModel implements FavoriteStore by means of the supplied favorites constructor parameter. Hence, even though we have no functions implemented directly on ItemViewModel, we can still call isFavorite() and toggleFavorite() — those calls get passed along to the favorites delegate object.

Tags:
Run Edit